//
//  TaskCollector.m
//  TaskManager
//
//  Created by Dmitriy on 03.06.13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "TaskCollector.h"
#import "Task.h"

@implementation TaskCollector

static TaskCollector* instance=nil;

+(TaskCollector*)sharedInstance
{
    if (instance==nil) {
        instance = [[TaskCollector alloc]init];
    }
//    return [instance autorelease];
    return instance;
}

-(id) init
{
    self = [super init];
    if(self!=nil)
    {
        tasksCollection = [[NSMutableArray alloc]init];
    }
    [self fill];
    return self;
}

-(void) dealloc
{
    [self saveTasksToFile];
    [tasksCollection release];
    [super dealloc];
}

-(void)fill
{
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[self saveFilePath]];
    
	if (fileExists) [self loadTasksFromFile];
    else
    {
        Task *task = [[Task alloc] initWithName:@"Task 1" time:[NSDate date]];
        [self appendTask:task];
        [task release];
        task = [[Task alloc]initWithName:@"Task 2" time:[NSDate dateWithTimeIntervalSinceNow:120]];
        [self appendTask:task];
        [task release];
    }
}

-(Task*) getTaskWithIndex:(int)index
{
    return (Task*)[tasksCollection objectAtIndex:index];
}

-(void) appendTask:(Task*)task
{
    [tasksCollection addObject:task];
}

-(int) getAmountOfTasks
{
    return [tasksCollection count];
}

-(void) deleteTaskWithIndex:(int)index
{
    [tasksCollection removeObjectAtIndex:index];
}

-(NSString*) saveFilePath
{
    NSArray *path =
	NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
	return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];
}

-(void) saveTasksToFile
{
    BOOL success = NO;
    NSString* filepath = [self saveFilePath];
    BOOL a = [[NSFileManager defaultManager] isWritableFileAtPath:filepath];
    Task* taks = [tasksCollection objectAtIndex:0];
    
    success = [tasksCollection writeToFile:filepath atomically:NO];
}

-(void) loadTasksFromFile
{
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[self saveFilePath]];
    
	if (fileExists)
    {
		NSMutableArray *tempArray = [[NSMutableArray alloc] initWithContentsOfFile:[self saveFilePath]];
        if(tempArray!=nil) [tasksCollection addObjectsFromArray:tempArray];
        [tempArray release];
    }
}

//#pragma mark NSCoding
//
//-(id) initWithCoder:(NSCoder *)aDecoder
//{
//    self = [super init];
//    if(self)
//    {
//        tasksCollection = [aDecoder decodeObjectForKey:@"TasksCollection"];
//    }
//    return self;
//}
//
//-(void) encodeWithCoder:(NSCoder *)aCoder
//{
//    [aCoder encodeObject:tasksCollection forKey:@"TasksCollection"];
//}

@end
